package com.fnzn.entranceGuard.schedule;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.fnzn.entranceGuard.constant.GuardConstant;
import com.fnzn.entranceGuard.entity.GuardIcInfo;
import com.fnzn.entranceGuard.entity.power.PowerDevice;
import com.fnzn.entranceGuard.entity.power.PowerException;
import com.fnzn.entranceGuard.mapper.GuardDeviceMapper;
import com.fnzn.entranceGuard.mapper.GuardIcDeviceMapper;
import com.fnzn.entranceGuard.mapper.GuardIcInfoMapper;
import com.fnzn.entranceGuard.mapper.UnitHouseVoMapper;
import com.fnzn.entranceGuard.mapper.power.PowerExceptionMapper;
import com.fnzn.entranceGuard.rest.guard.UsrUtil;
import com.fnzn.entranceGuard.rest.usrCloud.UsrApi;
import com.fnzn.entranceGuard.service.power.IPowerDeviceService;
import com.fnzn.entranceGuard.service.power.impl.PowerDeviceServiceImpl;
import com.fnzn.entranceGuard.util.DateTools;
import com.fnzn.entranceGuard.vo.GuardDeviceVo;
import com.fnzn.entranceGuard.vo.GuardIcDeviceVo;
import com.fnzn.entranceGuard.vo.UnitHouseVo;
import javassist.expr.NewArray;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.thymeleaf.util.ListUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author wf_sxf@163.com
 * @date 2018-06-07 8:46
 */
@Slf4j
@Component
public class    ScheduledTasks {

    @Autowired
    private GuardDeviceMapper guardDeviceMapper;
    @Autowired
    private GuardIcDeviceMapper guardIcDeviceMapper;
    @Autowired
    private GuardIcInfoMapper guardIcInfoMapper;
    @Autowired
    private UnitHouseVoMapper unitHouseVoMapper;
    @Autowired
    private IPowerDeviceService powerDeviceService;
    @Autowired
    private PowerExceptionMapper exceptionMapper;

    private static final SimpleDateFormat formate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

 /*   @Scheduled(fixedRate = 5000)
    public void scheduledDemo(){
        log.info("scheduled - fixedRate - print time every 5 seconds:{}", formate.format(new Date()) );
    }*/

    /**
     * "0/5 * *  * * ?"   每5秒触发
     * "0 0 12 * * ?"    每天中午十二点触发
     * "0 15 10 ? * *"    每天早上10：15触发
     * "0 15 10 * * ?"    每天早上10：15触发
     * "0 15 10 * * ? *"    每天早上10：15触发
     * "0 15 10 * * ? 2005"    2005年的每天早上10：15触发
     * "0 * 14 * * ?"    每天从下午2点开始到2点59分每分钟一次触发
     * "0 0/5 14 * * ?"    每天从下午2点开始到2：55分结束每5分钟一次触发
     * "0 0/5 14,18 * * ?"    每天的下午2点至2：55和6点至6点55分两个时间段内每5分钟一次触发
     * "0 0-5 14 * * ?"    每天14:00至14:05每分钟一次触发
     * "0 10,44 14 ? 3 WED"    三月的每周三的14：10和14：44触发
     * "0 15 10 ? * MON-FRI"    每个周一、周二、周三、周四、周五的10：15触发
     */
    //@Scheduled(cron="0 0/9 *  * * ?")
    public void scheduledCronDemo() {
        log.info("有人云定时任务", formate.format(new Date()));
        String data = "55,01,11,00,00,00,01,68";
        try {
            UsrUtil.publishForDevId(data, UsrUtil.device_id);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 定时任务 每小时根据设备定时更新IC卡
     */
    //@Scheduled(cron= "0 0 0/1 * * ?")
    public void scheduledDevice() {
        try {
            List<GuardDeviceVo> list = guardIcDeviceMapper.getGuardDeviceVo();
            if (!ListUtils.isEmpty(list)) {
                String deviceNumber;//设备号
                String type;//设备类型
                List<GuardIcInfo> guardIcInfoList;
                for (GuardDeviceVo guardDeviceVo : list) {
                    deviceNumber = guardDeviceVo.getDeviceNumber();
                    type = guardDeviceVo.getType();
                    guardIcInfoList = guardDeviceVo.getGuardIcInfoList();
                    if (!ListUtils.isEmpty(guardIcInfoList)) {
                        for (GuardIcInfo guardIcInfo : guardIcInfoList) {
                            List<GuardIcInfo> guardIcInfos = new ArrayList<>();
                            guardIcInfos.add(guardIcInfo);
                            //先查看设备在不在线
                            if (UsrApi.getDevice(deviceNumber)) {
                                if (StringUtils.isNotBlank(guardIcInfo.getHouseOwnerId())) {
                                    UsrUtil.addOrDelIcToDev(guardIcInfos, deviceNumber, GuardConstant.TYPE_ADD, type, null);
                                } else {
                                    UsrUtil.addOrDelIcToDev(guardIcInfos, deviceNumber, GuardConstant.TYPE_ADD, type, "Admin");
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 定时任务 每天零时查询物业费，欠费删除设备中IC卡
     */
    //@Scheduled(cron = "0 0 0 * * ?")
    public void scheduledIc() {
        log.info("--------定时任务:每天零时删除设备中应删除的IC卡------------");
        try {
            List<UnitHouseVo> list = unitHouseVoMapper.getList();
            if (!ListUtils.isEmpty(list)) {
                for (UnitHouseVo unitHouseVo : list) {
                    String houseId = unitHouseVo.getId();
                    if (unitHouseVo.getProertyEndtime() != null) {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        Date endDate = sdf.parse(sdf.format(unitHouseVo.getProertyEndtime()));
                        Date currentDate = sdf.parse(sdf.format(new Date()));
                        if (currentDate.getTime() > endDate.getTime()) {//已欠费
                            //讲IC卡状态修改为 欠费已停用
                            List<GuardIcDeviceVo> guardIcDeviceVoList = unitHouseVoMapper.getGuardIcDeviceVoByHouseId(houseId);
                            for (GuardIcDeviceVo guardIcDeviceVo : guardIcDeviceVoList) {
                                //修改状态为欠费已停用
                                guardIcDeviceMapper.updateStatusTo4ById(guardIcDeviceVo.getId());

                                String deviceNumber = guardIcDeviceVo.getDeviceNumber();
                                GuardIcInfo guardIcInfo = new GuardIcInfo();
                                List<GuardIcInfo> guardIcInfoList = new ArrayList<>();
                                guardIcInfo.setIcId(guardIcDeviceVo.getIcId());
                                guardIcInfoList.add(guardIcInfo);
                                guardIcDeviceVo.getId();
                                if (UsrApi.getDevice(deviceNumber)) {
                                    UsrUtil.addOrDelIcToDev(guardIcInfoList, deviceNumber, GuardConstant.TYPE_DEL, "0", null);
                                }
                            }
                        }
                    }
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 定时任务 每天零时查询物业费，欠费删除设备中IC卡
     *
     */
    @Scheduled(cron="0 0/30 *  * * ?")
    public void scheduledPower(){
        log.info("--------定时任务:间隔半小时查询电表情况------------");
        try {
             List<PowerDevice> powers =   powerDeviceService.selectList(new EntityWrapper<>());
             for(PowerDevice device : powers ){
                 int interval = DateTools.datePoorDiffMinute(device.getUpdateTime(), new Date());
                 log.info(interval+"");
                 if (interval > 60) {
                     PowerException exception = new PowerException();
                     exception.setDeviceId(device.getDeviceId());
                     exception.setPowerId(device.getPowerId());
                     exception.setTitle(device.getPowerName()+"断电或离线");
                     exception.setDescription(device.getPowerName()+"断电或离线,请及时检查。");
                     exceptionMapper.insert(exception);
                 }
             }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
